from typing import Optional, List, Tuple
from tortoise.exceptions import DoesNotExist
from app.modules.users.models import UserModel
from app.modules.users.schemas import UserCreateInput, UserCreatedResponse, UserUpdate, UserInfo
from app.core.exceptions import BusinessException, NotFoundException
from app.core.security import get_password_hash
from tortoise.exceptions import IntegrityError
from passlib.hash import bcrypt

async def create_first_superuser():
    """
    检查并创建第一个超级管理员账户
    """
    admin_exists = await UserModel.filter(username="admin", is_superuser=True).exists()
    if not admin_exists:
        hashed_password = bcrypt.hash("admin123")
        await UserModel.create(
            username="admin",
            password=hashed_password,
            nickname="超级管理员",
            is_active=True,
            is_superuser=True,
        )
        print("超级管理员 'admin' 创建成功，初始密码 'admin123'")

class UserService:
    """用户服务类"""

    @staticmethod
    async def get_by_username(username: str) -> Optional[UserModel]:
        """根据用户名获取用户"""
        return await UserModel.get_or_none(username=username)

    @staticmethod
    async def get_by_id(user_id: int) -> Optional[UserModel]:
        """根据ID获取用户"""
        return await UserModel.get_or_none(id=user_id)

    @staticmethod
    async def get_user_list(skip: int = 0, limit: int = 10) -> Tuple[int, List[UserModel]]:
        """获取用户列表"""
        total = await UserModel.all().count()
        users = await UserModel.all().offset(skip).limit(limit)
        # 将 Tortoise ORM 对象转换为 Pydantic 模型列表
        user_info_list = [UserInfo.from_orm(user) for user in users]
        return total, user_info_list

    @staticmethod
    async def create_user(user_in: UserCreateInput) -> UserCreatedResponse:
        """创建用户"""
        # 检查用户名是否已存在
        existing_user = await UserModel.get_or_none(username=user_in.username)
        if existing_user:
            raise BusinessException(message="用户名已存在")
        
        # 创建用户
        user = await UserModel.create(
            username=user_in.username,
            password=get_password_hash(user_in.password),
            nickname=user_in.nickname,
            # email=user_in.email # 暂时注释掉，因为输入模型里还没有
        )
        return UserCreatedResponse(username=user.username)

    @staticmethod
    async def update_user(user_id: int, user_in: UserUpdate) -> UserInfo:
        """更新用户信息"""
        user = await UserService.get_by_id(user_id)
        
        # 只更新传入的字段
        update_data = user_in.dict(exclude_unset=True)
        if update_data:
            await user.update_from_dict(update_data).save()
        
        return UserInfo.from_orm(user)

    @staticmethod
    async def delete_user(user_id: int) -> None:
        """删除用户"""
        user = await UserService.get_by_id(user_id)
        await user.delete()
